package org.gitos.cloud.comet.logic.recTcpLogic;

import org.gitos.cloud.comet.logic.AbstractTcpLogicHandler;
import org.gitos.cloud.comet.logic.ContextLogicHandler;
import org.gitos.cloud.comet.logic.LogicLoop;
import org.gitos.cloud.comet.mq.PushManager;
import org.gitos.cloud.domain.comm.Constant;
import org.gitos.cloud.domain.mq.MqMsg;
import org.gitos.cloud.domain.tcp.Bucket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * Created by shizhengchu on 16/3/18.
 */
@Component
public class PushToServerHandler extends AbstractTcpLogicHandler {

    private static final Logger log = LoggerFactory.getLogger(PushToServerHandler.class);

    @Autowired
    private PushManager pushManager;

    @Value("${" + Constant.NODE_ID + "}")
    private String nodeId;

    @Override
    public void tcplogic(ContextLogicHandler ctx) {
        Bucket bucket = ctx.getPipline().getBucket();
        Runnable runnable = new PushToServer(nodeId, pushManager, bucket);
        LogicLoop.fixThreadPool.execute(runnable);
        super.tcplogic(ctx);
    }
    /**
     * Created by shizhengchu on 15/12/7.
     * 推送到逻辑服务器的默认处理方法
     */
    static class PushToServer implements Runnable {
        private static final Logger log = LoggerFactory.getLogger(PushToServer.class);

        private static final String routeKey = "default";
        private String nodeId;
        private PushManager pushManager;
        private Bucket bucket;

        public PushToServer(String nodeId, PushManager pushManager, Bucket bucket) {
            this.nodeId = nodeId;
            this.pushManager = pushManager;
            this.bucket = bucket;
        }

        @Override
        public void run() {
            try {
                log.info("default event");
                MqMsg pushMsg = new MqMsg();
                pushMsg.setEvent(bucket.getCmd());
                pushMsg.setChannelId(bucket.getCtx().channel().id().asLongText());
                pushMsg.setNodeId(nodeId);
                pushMsg.setBucket(bucket);
                pushMsg.setPubIp( ((InetSocketAddress) bucket.getCtx().channel().remoteAddress()).getAddress().getHostAddress());
                pushManager.sendMsg(routeKey, pushMsg);
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}


